package com.mlh.json;

import com.mlh.json.entity.Dog;
import com.mlh.json.entity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
public class JsonHandler {
    // 1.目标方法@ResponseBody,表返回的数据是json格式
    // 2. springmvc 底层根据目标方法@ResponseBody,返回指定格式，根据的http 清求来进行处理
    // 3.底层原理我们在前面自定义@ResponseBody讲过，这里原生的springmvc使用转换器
    // 4. HttpMessageConverter
    @RequestMapping("/json/dog")
    @ResponseBody
    public Dog getJson(){
        // 返回对象
        // springmvc会根据你的设置，转成json格式数据返回
        Dog dog = new Dog();
        dog.setName("大黄狗");
        dog.setAddress("小新的家");
        return dog;
    }

    @RequestMapping("/save2")
    @ResponseBody
    // 1. @RequestBody User user在形参指定了@RequestBody
    // 2. springmvc 就会将提交的json字符串数据填充给指定Javabean
    public User save2(@RequestBody User user){
        System.out.println(user);
        return user;
    }

    //返回对象集合 以json格式
    @RequestMapping(value = "/json/dogs" )
    @ResponseBody
    public List<Dog> getJsons() {
        List<Dog> dogs = new ArrayList<>();
        dogs.add(new Dog("大黄狗", "小新的家"));
        dogs.add(new Dog("大黄狗2", "小新2的家"));
        dogs.add(new Dog("大黄狗3", "小新3的家"));
        return dogs;
    }

    //响应用户下载文件的请求
    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws IOException {
        //1. 先获取到下载文件的inputstream
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/img/smalldog.jpg");
        //2.开辟一个存放文件的byte数组,这里老师使用byte[]是可以支持二进制数据(图片，视频。)
        byte[] bytes = new byte[resourceAsStream.available()];
        //3.将下载文件的数据，读入到byte[]
        resourceAsStream.read(bytes);
        //ResponseEntity构造器
        //public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
        //         this(body, headers, (Object)status);
        //     }
        //4.创建返回的HttpStatus
        HttpStatus httpStatus=HttpStatus.OK;
        //5.创建headers
        HttpHeaders httpHeaders = new HttpHeaders();
        //指定返回的数据，客户端应当以附件形式处理
        httpHeaders.set("Content-Disposition","attachment;filename=smalldog.jpg");
        ResponseEntity responseEntity = new ResponseEntity(bytes,httpHeaders,httpStatus);
        return responseEntity;
    }
}
